package com.web;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据源工具类
 */
public class DataSourceUtils {

    //数据源
    private static DataSource dataSource;

    // 静态代码块，类加载时读取配置文件，并且创建数据源对象
    static{
        // 创建Properties对象
        Properties properties = new Properties();
        // 加载配置文件
        try {
            properties.load(DataSourceUtils.class.getClassLoader()
                    .getResourceAsStream("druid.properties"));
            //创建数据源
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection(){
        if(dataSource != null){
            try {
                return dataSource.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
